﻿using DevExpress.ExpressApp.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Users;
using YAPACS.Organizations;

namespace YAPACS.RisServer.Controllers;

[Authorize]
public class AccountController : AbpController
{
    private readonly ICurrentUser _currentUser;
    private readonly ICurrentUserOrganization _currentUserOrganization;
    private readonly IRepository<ApplicationUser, Guid> _userRepository;
    private readonly SignInManager _signInManager;

    public AccountController(
        ICurrentUser currentUser,
        IRepository<ApplicationUser, Guid> userRepository,
        ICurrentUserOrganization currentUserOrganization,
        SignInManager signInManager)
    {
        _currentUser = currentUser;
        _userRepository = userRepository;
        _currentUserOrganization = currentUserOrganization;
        _signInManager = signInManager;
    }

    [HttpGet]
    [AllowAnonymous]
    [Route("api/user-groups")]
    public async Task<IActionResult> GetUserGroups(string userName)
    {
        if (!string.IsNullOrWhiteSpace(userName))
        {
            var user = await _userRepository.FirstOrDefaultAsync(x => x.UserName == userName);
            if (user != null)
            {
                var userGroups = user.UserGroups
                    .OrderBy(g => g.Department.Institution.Name)
                    .ThenBy(g => g.Department.Name)
                    .ThenBy(g => g.Name)
                    .ToList();

                var defaultUserGroup = user.DefaultUserGroup;
                if (defaultUserGroup == null && userGroups.Count == 1)
                {
                    defaultUserGroup = userGroups.First();
                }

                return Ok(userGroups.Select(g =>
                {
                    var groupName = g.Name;

                    if (userGroups.GroupBy(g => g.Department.Institution.Name).Count() > 1)
                    {
                        groupName = $"{g.Name}/{g.Department.Name}/{g.Department.Institution.Name}";
                    }
                    else if (userGroups.GroupBy(g => g.Department.Name).Count() > 1)
                    {
                        groupName = $"{g.Name}/{g.Department.Name}";
                    }

                    return new
                    {
                        id = $"{g.Id}@{g.Department.Id}@{g.Department.Institution.Id}@{g.Name}",
                        name = groupName,
                        isDefault = defaultUserGroup != null && defaultUserGroup.Id == g.Id
                    };
                }));
            }
        }
        return Ok();
    }

    [AllowAnonymous]
    [HttpGet("api/get-permissions")]
    public async Task<IActionResult> GetPermissions()
    {
        if (User.Identity.IsAuthenticated)
        {
            var user = await _userRepository.GetAsync(_currentUserOrganization.UserId);
            var permissions = user.GetUserPermissions().Select(e => e.Name);
            return Ok(permissions);
        }
        else
        {
            return Ok();
        }
    }

    [HttpPost("api/change-password")]
    public async Task<IActionResult> ChangePassword(string currentPassword, string newPassword)
    {
        var authResult = _signInManager.AuthenticateByLogonParameters(new OrganizationLogonParameters(_currentUser.UserName, currentPassword));
        if (authResult.Succeeded)
        {
            var user = await _userRepository.GetAsync(_currentUserOrganization.UserId);
            user.SetPassword(newPassword);
            return Ok(new { success = true });
        }
        return Ok(new
        {
            success = false,
            error = "当前密码不正确"
        });
    }
}
